package cn.jhc.servlet;

import cn.jhc.bean.Question;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/profile.do")
public class ProfileServlet extends HttpServlet {
    private static final String CONNECTION_URL = "jdbc:mysql://localhost/questions?user=quser&password=123456&serverTimezone=GMT";
    private static final String SQLString = "select id, name, username, email, subject, message, agree from question";
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Question> questions = new ArrayList<>();
        //数据库表的一行对应一个Java对象，数据库一个表对应Java的一个List对象
        try(Connection connection = DriverManager.getConnection(CONNECTION_URL)) {
            try(Statement statement = connection.createStatement()) {
                try(ResultSet resultSet = statement.executeQuery(SQLString)) {
                    while (resultSet.next()) {
                        Question q = new Question();
                        q.setId(resultSet.getInt(1));
                        q.setName(resultSet.getString(2));
                        q.setUsername(resultSet.getString(3));
                        q.setEmail(resultSet.getString(4));
                        q.setSubject(resultSet.getString(5));
                        q.setMessage(resultSet.getString(6));
                        q.setAgree(resultSet.getBoolean(7));
                        questions.add(q);
                    }
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        Gson gson = new Gson();
        resp.setContentType("application/json");
        resp.getWriter().println(gson.toJson(questions));
    }
}
